<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="搜索内容" prop="searchContent">
        <el-input
          v-model="queryParams.searchContent"
          placeholder="请输入场站ID或信息对象地址或设备ID或描述"
          clearable
          style="width: 400px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="场站ID" prop="stationId">
        <el-select
          v-model="queryParams.stationId"
          placeholder="场站ID"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in this.stationList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select
          v-model="queryParams.equipmentType"
          placeholder="设备类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in this.equipmentTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="匹配类型" prop="matchType">
        <el-select
          v-model="queryParams.matchType"
          placeholder="匹配类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.point_reflection_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="onlineEnable">
        <el-select
          v-model="queryParams.onlineEnable"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="multiple"
          @click="handleCopyAdd"
        >复制新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteByStation"
        >按场站删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >按场站导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <!-- 自增序号列 -->
      <el-table-column type="index" label="序号">
        <!-- 自定义索引 (可选) -->
        <template slot-scope="scope">
          {{ serial_number + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="场站ID" align="center" key="stationId" prop="stationId" v-if="columns[1].visible"
                       width="160" :show-overflow-tooltip="true"/>
      <el-table-column label="场站名称" align="center" key="stationName" prop="stationName" v-if="columns[1].visible"
                       width="160" :show-overflow-tooltip="true"/>
      <el-table-column label="信息对象地址" align="center" key="infoObjAddr" prop="infoObjAddr" v-if="columns[2].visible"
                       width="160" :show-overflow-tooltip="true"/>
      <el-table-column label="协议名称" align="center" key="protocolName" prop="protocolName" v-if="columns[3].visible"
                       width="120"/>
      <el-table-column label="属性" align="center" key="propertyName" prop="propertyName" v-if="columns[4].visible"
                       width="160"/>
      <el-table-column label="设备类型" align="center" key="equipmentType" prop="equipmentType" v-if="columns[5].visible"
                       width="100"/>
      <el-table-column label="设备ID" align="center" key="equipmentId" prop="equipmentId" v-if="columns[6].visible"
                       width="120"/>
      <el-table-column label="系数" align="center" key="factor" prop="factor" v-if="columns[7].visible" width="80"/>
      <el-table-column label="常量" align="center" key="constant" prop="constant" v-if="columns[8].visible" width="120"/>
      <el-table-column label="表达式" align="center" key="expression" prop="expression" v-if="columns[9].visible"
                       width="130"/>
      <el-table-column label="自定义函数" align="center" key="udf" prop="udf" v-if="columns[10].visible" width="100"/>
      <el-table-column label="返回类型" align="center" key="resultType" prop="resultType" v-if="columns[11].visible"
                       width="120"/>
      <el-table-column label="电池柜" align="center" key="cab" prop="cab" v-if="columns[12].visible" width="120"/>
      <el-table-column label="电池堆" align="center" key="stack" prop="stack" v-if="columns[13].visible" width="120"/>
      <el-table-column label="电池簇" align="center" key="cluster" prop="cluster" v-if="columns[14].visible" width="120"/>
      <el-table-column label="电池组" align="center" key="pack" prop="pack" v-if="columns[15].visible" width="160"/>
      <el-table-column label="单体" align="center" key="cell" prop="cell" v-if="columns[16].visible" width="170"/>
      <el-table-column label="描述" align="center" key="description" prop="description" v-if="columns[17].visible"
                       width="160" :show-overflow-tooltip="true"/>
      <el-table-column label="标准描述" align="center" key="standardDescription" prop="standardDescription"
                       v-if="columns[18].visible" width="160" :show-overflow-tooltip="true"/>
      <el-table-column label="初始属性名" align="center" key="initPropertyName" prop="initPropertyName"
                       v-if="columns[19].visible" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="是否填充" align="center" key="fillData" prop="fillData" v-if="columns[20].visible"
                       width="120"/>
      <el-table-column label="备注" align="center" key="comment" prop="comment" v-if="columns[21].visible" width="120"/>
      <el-table-column label="单位" align="center" key="unit" prop="unit" v-if="columns[22].visible" width="80"/>
      <el-table-column label="数值标记" align="center" key="remark" prop="remark" v-if="columns[23].visible" width="80"/>
      <el-table-column label="状态" align="center" key="status" v-if="columns[24].visible">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.onlineEnable"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="映射字段" align="center" key="mapField" prop="mapField" v-if="columns[25].visible"
                       width="160"/>
      <el-table-column label="映射类型" align="center" key="reflectionType" prop="reflectionType" v-if="columns[26].visible"
                       width="120">
        <template slot-scope="scope">
          <div>
            <div v-if="scope.row.reflectionType === '0'">没有匹配</div>
            <div v-else-if="scope.row.reflectionType === '1'">一个匹配</div>
            <div v-else>多个匹配</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[27].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.id !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:point:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:point:remove']"
          >删除
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                       v-hasPermi="['system:point:handleStandardField','system:point:handleStandardField', 'system:point:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleMapField" icon="el-icon-key"
                                v-hasPermi="['system:point:handleMapField']">匹配字段
              </el-dropdown-item>
              <el-dropdown-item command="handleStandardField" icon="el-icon-key"
                                v-hasPermi="['system:point:handleStandardField']">匹配属性
              </el-dropdown-item>
              <el-dropdown-item command="handleExpression" icon="el-icon-key"
                                v-hasPermi="['system:point:handleStandardField']">生成表达式
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改点表配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="场站ID" prop="stationId">
              <el-input v-model="form.stationId" maxlength="30" :disabled = "this.disabled"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentType">
              <el-input v-model="form.equipmentType" maxlength="30" :disabled = "this.disabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信息对象地址" prop="infoObjAddr">
              <el-input v-model="form.infoObjAddr" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标准描述" prop="standardDescription">
              <el-input v-model="form.standardDescription" maxlength="50" :disabled = "this.disabled"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="协议名" prop="protocolName">
              <el-input v-model="form.protocolName" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备ID" prop="equipmentId">
              <el-input v-model="form.equipmentId" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="系数" prop="factor">
              <el-input v-model="form.factor" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="常量" prop="constant">
              <el-input v-model="form.constant" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="自定义函数" prop="udf">
              <el-input v-model="form.udf" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表达式" prop="expression">
              <el-input v-model="form.expression" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="属性名" prop="propertyName">
              <el-input v-model="form.propertyName" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="映射字段" prop="mapField">
              <el-input v-model="form.mapField" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="初始属性名" prop="propertyName">
              <el-input v-model="form.initPropertyName" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否填充" prop="mapField">
              <el-input v-model="form.fillData" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.onlineEnable">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  changePointStatus,
  delPoint,
  delPointByStationId,
  getPoint,
  handlePointExpression,
  listPoint,
  matchMapField,
  matchStandardField,
  batchDelPoint, addPoint, updatePoint
} from "@/api/system/point";
import {getEquipmentDictList, getStationDictList}
  from "@/api/system/dict";

export default {
  name: "Check",
  dicts: ['sys_normal_disable', 'point_reflection_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      disabled: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: [],
      equipmentTypeList: [],
      stationList:[],
      // 场站
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        id: undefined,
        standardDescription: undefined,
        initPropertyName: undefined,
        fillData: undefined,
        mapField: undefined,
        equipmentType: undefined,
        equipmentId: undefined,
        protocolName: undefined,
        udf: undefined
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        manufacturer: undefined,
        stationId: undefined,
        equipmentType: undefined,
        matchType: undefined,
        onlineEnable: undefined,
        searchContent: undefined
      },
      // 列信息
      columns: [
        {key: 0, label: `编号`, visible: true},
        {key: 1, label: `场站ID`, visible: true},
        {key: 2, label: `信息对象地址`, visible: true},
        {key: 3, label: `协议名称`, visible: true},
        {key: 4, label: `属性名称`, visible: true},
        {key: 5, label: `设备类型`, visible: true},
        {key: 6, label: `设备id`, visible: true},
        {key: 7, label: `系数`, visible: true},
        {key: 8, label: `常量`, visible: true},
        {key: 9, label: `表达式`, visible: true},
        {key: 10, label: `自定义函数`, visible: true},
        {key: 11, label: `返回类型`, visible: true},
        {key: 12, label: `电池柜`, visible: true},
        {key: 13, label: `电池堆`, visible: true},
        {key: 14, label: `电池簇`, visible: true},
        {key: 15, label: `电池组`, visible: true},
        {key: 16, label: `单体`, visible: true},
        {key: 17, label: `描述`, visible: true},
        {key: 18, label: `标准描述`, visible: true},
        {key: 19, label: `初始属性名`, visible: true},
        {key: 20, label: `是否填充`, visible: true},
        {key: 21, label: `备注`, visible: true},
        {key: 22, label: `单位`, visible: true},
        {key: 23, label: `数值标记`, visible: true},
        {key: 24, label: `状态`, visible: true},
        {key: 25, label: `映射字段`, visible: true},
        {key: 26, label: `映射类型`, visible: true},
        {key: 27, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户名称不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ]
      }
    };
  },
  computed: {
    serial_number() {
      return this.queryParams.pageSize * (this.queryParams.pageNum - 1);
    }
  },
  created() {
    this.queryParams.stationId = this.$route.params.stationId;
    this.getStationList();
    this.getEquipmentList();
    this.getList();
  },
  methods: {
    getStationList() {
      getStationDictList().then(response => {
        let rows = response.data;
        this.stationList = rows.map(style => ({
          value: style.stationId,
          label: style.stationName,
        }));
      });
    },
    getEquipmentList() {
      getEquipmentDictList().then(response => {
        let rows = response.data;
        this.equipmentTypeList = rows.map(style => ({
          value: style.id,
          label: style.name,
        }));
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPoint(this.queryParams).then(response => {
          this.dataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.onlineEnable === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.description + '"吗？').then(function () {
        return changePointStatus(row.id, row.onlineEnable);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.onlineEnable = row.onlineEnable === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        standardDescription: undefined,
        initPropertyName: undefined,
        fillData: undefined,
        mapField: undefined,
        equipmentType: undefined,
        equipmentId: undefined,
        protocolName: undefined,
        udf: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disabled = false;
      this.open = true;
    },
    handleCopyAdd(){
      const ids = this.ids;
      if (ids.length > 1){
        this.$modal.msgWarning("只能选择一个");
        return;
      }
      const id = ids[0];
      this.disabled = false;
      this.reset();
      getPoint(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改点表信息";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disabled = true;
      const id = row.id || this.ids;
      getPoint(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改点表信息";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePoint(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPoint(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除编号为"' + row.id + '"的数据项？').then(function () {
        return delPoint(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleBatchDelete(){
      const ids = this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return batchDelPoint(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDeleteByStation(row) {
      const stationId = this.queryParams.stationId;
      if (stationId === '' || stationId === undefined){
        this.$modal.msgError("请选择要删除的场站");
        return;
      }
      this.$modal.confirm('是否确认删除场站ID为"' + stationId + '"的数据项？').then(function () {
        return delPointByStationId(stationId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 映射按钮操作 */
    handleMapField(row) {
      this.$modal.confirm('是否确认匹配编号为"' + row.id + '"的字段？').then(function () {
        return matchMapField(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleStandardField(row) {
      this.$modal.confirm('是否确认匹配编号为"' + row.id + '"的属性名？').then(function () {
        return matchStandardField(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleExpression(row) {
      this.$modal.confirm('是否确认重新生成"' + row.id + '"的表达式？').then(function () {
        return handlePointExpression(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("生成成功");
      }).catch(() => {
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleMapField":
          this.handleMapField(row);
          break;
        case "handleStandardField":
          this.handleStandardField(row);
          break;
        case "handleExpression":
          this.handleExpression(row);
          break;
        default:
          break;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/point/exportPointData', {
        ...this.queryParams
      }, `point_tool_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
